package com.example.jpatest3;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class AddPoemer extends Thread{
    int min;
    int max;
    List<String> urlList;

    BookLuoWRRepository bookLuoWRRepository;

    public AddPoemer(List<String> urlList,
                     int min, int max
    , BookLuoWRRepository bookLuoWRRepository){
        this.min = min;
        this.max = max;
        this.urlList = urlList;
        this.bookLuoWRRepository =
                bookLuoWRRepository;
    }

    //320
    //32线程 10
    @Override
    public void run() {
        super.run();
        for(int i=min;i<=max;i++){
            String html1 = null;
            try {
                html1 = AddPoem.getHTML(
                        "https://so.gushiwen.cn/"+
                        urlList.get(i));
                String reg = "<h1.*?>(.*?)</h1>";
                Pattern r2 = Pattern.compile(reg);
                Matcher m2 = r2.matcher(html1);
                String bookName="";
                if(m2.find()){
                    bookName = m2.group(1);
                }

                reg = "<div class=\"contson\".*?>(.*?)</div>";
                r2 = Pattern.compile(reg);
                m2 = r2.matcher(html1);
                Double bookPrice = 0.0;
                if(m2.find()){
                    bookPrice = Double.valueOf(m2.group(1).trim().length());
                }

                BookLuoWR book =
                        new BookLuoWR();
                book.setBookName(bookName);
                book.setBookPrice(bookPrice);
                bookLuoWRRepository.save(book);

                System.out.println(book);
                Thread.sleep(2000+
                        (int)(Math.random()*3000));
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
